package bb.lanxing.devices.sync;

import androidx.annotation.NonNull;
import bb.lanxing.calc.manager.SourceDataPool;
import com.github.mikephil.charting.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.calc.data.CadencePoint;
import bb.lanxing.calc.data.GpsPoint;
import bb.lanxing.calc.data.HeartratePoint;
import bb.lanxing.calc.data.PowerratePoint;
import bb.lanxing.calc.data.SourcePoint;
import bb.lanxing.calc.processer.ProcessorFactory;
import bb.lanxing.calc.processer.i.IWorkoutProcessor;
import bb.lanxing.model.WorkoutDatabaseHelper;
import bb.lanxing.model.database.DeviceInfo;
import bb.lanxing.model.database.Workout;
import bb.lanxing.util.Enums;
import bb.lanxing.util.Log;

public class BesSportProcessor {
	final private static String TAG = "BesSportProcessor";
	//public static final int BES_SYNC_ERROR = -1;
	public static final int BES_SYNC_STOPPED = 0;
	public static final int BES_SYNC_FINISHED = 1;
	public static final int BES_SYNC_DUPLICATED = 2;

	private static final long LONG_HIGH_MASK = 0x00000000FFFFFFFFL;

	private static final long HEAD_MAGIC_NUMBER1 = 0XFF01FF00L;

	private static final long HEAD_MAGIC_NUMBER2 = 0XFF03FF02L;

	private String address;
	private DeviceInfo deviceInfo;
	private String equipmentInfoJson;
	private int mSourceType;
	private final IWorkoutProcessor workoutProcessor = ProcessorFactory.create(ProcessorFactory.TYPE_STATIC);

	public BesSportProcessor(int deviceType) {
		this.mSourceType = deviceType;
	}

	public void setAddress(String deviceAddress) {
		this.address = deviceAddress;
	}

	public int getSourceType() {
		return this.mSourceType;
	}

	public static class CyclingWorkoutReader {

		public static CYCLING_WORKOUT_INFO_T readWorkoutInfo(String filePath) {
			CYCLING_WORKOUT_INFO_T workoutInfo = new CYCLING_WORKOUT_INFO_T();

			try {
				// 读取文件内容到字符串
				String fileContent = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

				// 解析JSON字符串
				JSONObject jsonObject = new JSONObject(fileContent);

				// 从JSON对象中获取字段并设置到workoutInfo对象
				workoutInfo.start_time = jsonObject.getLong("start_time");
				workoutInfo.end_time = jsonObject.getLong("end_time");
				workoutInfo.total_calorie = jsonObject.getInt("total_calorie");
				workoutInfo.total_duration = jsonObject.getInt("total_duration");
				workoutInfo.total_distance = jsonObject.getDouble("total_distance");
				workoutInfo.sports_duration = jsonObject.getInt("sports_duration");
				workoutInfo.pause_duration = jsonObject.getInt("pause_duration");
				workoutInfo.elevation_gain = jsonObject.getDouble("elevation_gain");
				workoutInfo.elevation_loss = jsonObject.getDouble("elevation_loss");
				workoutInfo.avg_hr_value = (byte) jsonObject.getInt("avg_hr_value");
				workoutInfo.max_hr_value = (byte) jsonObject.getInt("max_hr_value");
				workoutInfo.avg_cadence = jsonObject.getInt("avg_cadence");
				workoutInfo.max_cadence = jsonObject.getInt("max_cadence");
				workoutInfo.avg_speed = jsonObject.getDouble("avg_speed");
				workoutInfo.max_speed = jsonObject.getDouble("max_speed");
				workoutInfo.min_altitude = jsonObject.getDouble("min_altitude");
				workoutInfo.max_altitude = jsonObject.getDouble("max_altitude");
				workoutInfo.avg_power = jsonObject.getDouble("avg_power");
				workoutInfo.max_power = jsonObject.getDouble("max_power");
				workoutInfo.min_grade = jsonObject.getDouble("min_grade");
				workoutInfo.max_grade = jsonObject.getDouble("max_grade");
				workoutInfo.down_distance = jsonObject.getDouble("down_distance");
				workoutInfo.up_distance = jsonObject.getDouble("up_distance");
				workoutInfo.flat_distance = jsonObject.getDouble("flat_distance");
				workoutInfo.down_duration = jsonObject.getInt("down_duration");
				workoutInfo.up_duration = jsonObject.getInt("up_duration");
				workoutInfo.flat_duration = jsonObject.getInt("flat_duration");
				workoutInfo.sport_type = (short) jsonObject.getInt("sport_type");
				workoutInfo.uuid = jsonObject.optString("uuid");
			} catch (JSONException | IOException e) {
				Log.i("readWorkoutInfo exception = " + e.getMessage());
				throw new RuntimeException(e);
			}
			Log.d(TAG, "readWorkoutInfo: total_distance = " + workoutInfo.total_distance + ", duration = " + workoutInfo.total_duration + ",uuid = " + workoutInfo.uuid);
			return workoutInfo;
		}

		// CYCLING_WORKOUT_INFO_T类定义
		public static class CYCLING_WORKOUT_INFO_T {
			public long start_time;
			public long end_time;
			public int total_calorie;
			public int total_duration;
			public double total_distance;
			public int sports_duration;
			public int pause_duration;
			public double elevation_gain;
			public double elevation_loss;
			public byte avg_hr_value;
			public byte max_hr_value;
			public int avg_cadence;
			public int max_cadence;
			public double avg_speed;
			public double max_speed;
			public double min_altitude;
			public double max_altitude;
			public double avg_power;
			public double max_power;
			public double min_grade;
			public double max_grade;
			public double down_distance;
			public double up_distance;
			public double flat_distance;
			public long down_duration;
			public long up_duration;
			public long flat_duration;
			public short sport_type;
			public String uuid;
		}

		static CYCLING_WORKOUT_INFO_T mWorkoutInfo;

		private static void init(String workoutFileName) {
			Log.d(TAG, "CyclingWorkoutReader init: workoutFileName = " + workoutFileName);
			mWorkoutInfo = readWorkoutInfo(workoutFileName);
		}

		public static long getStartTime() {
			return mWorkoutInfo.start_time;
		}

		public static long getDuration() {
			return mWorkoutInfo.total_duration;
		}

		public static double getDistance() {
			return mWorkoutInfo.total_distance;
		}

		public static long getEndTime() {
			return mWorkoutInfo.end_time;
		}

		public static int getTotalCalorie() {
			return mWorkoutInfo.total_calorie;
		}

		public static int getTotalDuration() {
			return mWorkoutInfo.total_duration;
		}

		public static double getTotalDistance() {
			return mWorkoutInfo.total_distance;
		}

		public static int getSportsDuration() {
			return mWorkoutInfo.sports_duration;
		}

		public static int getPauseDuration() {
			return mWorkoutInfo.pause_duration;
		}

		public static double getElevationGain() {
			return mWorkoutInfo.elevation_gain;
		}

		public static double getElevationLoss() {
			return mWorkoutInfo.elevation_loss;
		}

		public static int getAvgHrValue() {
			return mWorkoutInfo.avg_hr_value;
		}

		public static int getMaxHrValue() {
			return mWorkoutInfo.max_hr_value;
		}

		public static int getAvgCadenceFreq() {
			return mWorkoutInfo.avg_cadence;
		}

		public static int getMaxCadenceFreq() {
			return mWorkoutInfo.max_cadence;
		}

		public static double getAvgSpeed() {
			return mWorkoutInfo.avg_speed;
		}

		public static double getMaxSpeed() {
			return mWorkoutInfo.max_speed;
		}

		public static double getMinAltitude() {
			return mWorkoutInfo.min_altitude;
		}

		public static double getMaxAltitude() {
			return mWorkoutInfo.max_altitude;
		}

		public static double getAvgPower() {
			return mWorkoutInfo.avg_power;
		}

		public static double getMaxPower() {
			return mWorkoutInfo.max_power;
		}

		public static double getMinGrade() {
			return mWorkoutInfo.min_grade;
		}

		public static double getMaxGrade() {
			return mWorkoutInfo.max_grade;
		}

		public static double getDownDistance() {
			return mWorkoutInfo.down_distance;
		}

		public static double getUpDistance() {
			return mWorkoutInfo.up_distance;
		}

		public static double getFlatDistance() {
			return mWorkoutInfo.flat_distance;
		}

		public static long getDownDuration() {
			return mWorkoutInfo.down_duration;
		}

		public static long getUpDuration() {
			return mWorkoutInfo.up_duration;
		}

		public static long getFlatDuration() {
			return mWorkoutInfo.flat_duration;
		}

		public static short getSportType() {
			return mWorkoutInfo.sport_type;
		}

		public static String getUuid() {
			return mWorkoutInfo.uuid;
		}
	}

	public static class TrackPointReader {

		// 假设结构体字段的字节大小，用于计算结构体的总大小
		private static final int SIZEOF_DOUBLE = 8;
		private static final int SIZEOF_UINT32_T = 4;
		private static final int SIZEOF_UINT16_T = 2;
		private static final int SIZEOF_UINT8_T = 1;
		private static final int STRUCTURE_SIZE = (11 * SIZEOF_DOUBLE) + 2 * SIZEOF_UINT32_T + 2 * SIZEOF_UINT16_T + 3 * SIZEOF_UINT8_T;

		public static List<TrackPointReader.CYCLING_TRACKPOINT_INFO_T> readTrackPoints(String filePath) {
			List<TrackPointReader.CYCLING_TRACKPOINT_INFO_T> trackPoints = new ArrayList<>();
			try (FileInputStream fis = new FileInputStream(filePath)) {
				ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
				if (fis.read(buffer.array()) != buffer.array().length) ;
				long header1 = buffer.getInt(0);

				buffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
				if (fis.read(buffer.array()) != buffer.array().length) ;
				long header2 = buffer.getInt(0);
				int version = 1;
				header1 &= LONG_HIGH_MASK;
				header2 &= LONG_HIGH_MASK;
				if (header1 == HEAD_MAGIC_NUMBER1 && header2 == HEAD_MAGIC_NUMBER2) {
					fis.skip(24);
					version = 2;
				} else {
					fis.skip(-8);
				}
				// 循环读取结构体直到文件结束
				while (true) {
					TrackPointReader.CYCLING_TRACKPOINT_INFO_T trackPointInfo = new TrackPointReader.CYCLING_TRACKPOINT_INFO_T();
					buffer = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
					// 读取double类型的字段
					for (int i = 0; i < 11; i++) {
						buffer.clear();
						if (fis.read(buffer.array()) != buffer.array().length) {
							break; // 如果读取的字节数不足，跳出循环
						}
						trackPointInfo.setField(i, buffer.getDouble(0));
					}

					// 读取uint32_t类型的字段
					buffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
					if (fis.read(buffer.array()) != buffer.array().length) {break;}
					trackPointInfo.time = buffer.getInt(0);

					buffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
					if (fis.read(buffer.array()) != buffer.array().length) {break;}
					trackPointInfo.duration = buffer.getInt(0);

					// 读取uint16_t类型的字段
					buffer = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
					if (fis.read(buffer.array()) != buffer.array().length) {break;}
					trackPointInfo.cur_cadence = buffer.getShort(0);

					buffer = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
					if (fis.read(buffer.array()) != buffer.array().length) {break;}
					trackPointInfo.wheelrpm = buffer.getShort(0);

					if (version == 2) {
						// 读取uint16_t类型的字段
						buffer = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
						if (fis.read(buffer.array()) != buffer.array().length) {break;}
						trackPointInfo.hr_cur = buffer.getShort(0);
					} else {
						// 读取uint8_t类型的字段
						int bytesRead = fis.read(); // 读取一个字节并存储结果
						if (bytesRead != -1) {
							trackPointInfo.hr_cur = bytesRead; // 使用存储的结果设置字段
						} else {
							// 如果读取的字节数不足或者已经到达文件末尾，则退出循环
							break;
						}
					}
					// 继续读取其他uint8_t类型的字段
					int bytesRead = fis.read();
					if (bytesRead != -1) {
						trackPointInfo.is_pause = (byte) bytesRead;
					} else {
						break;
					}

					bytesRead = fis.read();
					if (bytesRead != -1) {
						trackPointInfo.temperature = bytesRead;
					} else {
						break;
					}
					if (version == 1) {
						// v1 版本 字节对齐问题,所以跳过一个字节
						byte test = (byte) fis.read();
					}
					// 添加到列表
					trackPoints.add(trackPointInfo);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			Log.i(TAG, "readTrackPoints: trackPoints size = " + trackPoints.size());
			for (TrackPointReader.CYCLING_TRACKPOINT_INFO_T item : trackPoints) {
				if (item.cur_cadence < 0) {
					Log.i(TAG, "readTrackPoints: item = " + item);
				}
			}
			return trackPoints;
		}

		// CYCLING_TRACKPOINT_INFO_T结构体类定义
		public static class CYCLING_TRACKPOINT_INFO_T {
			public double accuracy;
			public double altitude;
			public double latitude;
			public double longitude;
			public double bearing;
			public double speed;
			public double distance;
			public double cur_slope;
			public double power;
			public double elevation_gain;
			public double elevation_loss;
			public int time;
			public int duration;
			public short cur_cadence;
			public short wheelrpm;
			public int hr_cur;
			public byte is_pause;
			public int temperature;

			// 根据索引设置字段的值
			public void setField(int index, double value) {
				switch (index) {
					case 0:
						accuracy = value;
						break;
					case 1:
						altitude = value;
						break;
					case 2:
						latitude = value;
						break;
					case 3:
						longitude = value;
						break;
					case 4:
						bearing = value;
						break;
					case 5:
						speed = value;
						break;
					case 6:
						distance = value;
						break;
					case 7:
						cur_slope = value;
						break;
					case 8:
						power = value;
						break;
					case 9:
						elevation_gain = value;
						break;
					case 10:
						elevation_loss = value;
						break;
					default:
						throw new IllegalArgumentException("无效的索引: " + index);
				}
			}

			public void setField(int index, int value) {
				switch (index) {
					case 11:
						time = value;
						break;
					case 12:
						duration = value;
						break;
					default:
						throw new IllegalArgumentException("无效的索引: " + index);
				}
			}

			// 为short类型添加：
			public void setField(int index, short value) {
				switch (index) {
					case 13:
						cur_cadence = value;
						break;
					case 14:
						wheelrpm = value;
						break;
					default:
						throw new IllegalArgumentException("无效的索引: " + index);
				}
			}

			// 为byte类型添加：
			public void setField(int index, byte value) {
				switch (index) {
					case 15:
						hr_cur = value;
						break;
					case 16:
						is_pause = value;
						break;
					case 17:
						temperature = value;
						break;
					default:
						throw new IllegalArgumentException("无效的索引: " + index);
				}
			}

			@NonNull @Override public String toString() {
				return "CYCLING_TRACKPOINT_INFO_T{" + "accuracy=" + accuracy + ", altitude=" + altitude + ", latitude=" + latitude + ", longitude=" + longitude + ", bearing=" + bearing + ", speed=" + speed + ", distance=" + distance + ", cur_slope=" + cur_slope + ", power=" + power + ", elevation_gain=" + elevation_gain + ", elevation_loss=" + elevation_loss + ", time=" + time + ", duration=" + duration + ", cur_cadence=" + cur_cadence + ", wheelrpm=" + wheelrpm + ", hr_cur=" + hr_cur + ", is_pause=" + is_pause + ", temperature=" + temperature + '}';
			}
		}

		static List<TrackPointReader.CYCLING_TRACKPOINT_INFO_T> mTrackPoints = null;

		private static void init(String trackpointFileName) {
			Log.d(TAG, "TrackPointReader init: trackpointFileName=" + trackpointFileName);
			mTrackPoints = TrackPointReader.readTrackPoints(trackpointFileName);
		}
	}

	public boolean ifFitFileSynced(String fitName) {
		Workout workFit = Workout.getByUuid(fitName);
		return workFit != null;
	}

	public interface BesSyncCallback {
		void onSyncCallback(String fitName, Integer result);
	}

	public void onStartProcess(String fileWorkout, String fileTrackpoint, BesSyncCallback syncCb) {
		Log.d(TAG, "onStartProcess start+++++");
		File fitFile = new File(fileWorkout);
		String fitName = fitFile.getName();
		Log.d(TAG, "onStartProcess fitName=" + fitName);
		CyclingWorkoutReader.init(fileWorkout);
		String uuid = CyclingWorkoutReader.getUuid();
		boolean isSynced = ifFitFileSynced(uuid);
		if (isSynced) {
			Log.w(TAG, "onStartProcess, EXIT!!! already synced!");
			if (syncCb != null) {
				syncCb.onSyncCallback(fitName, BES_SYNC_DUPLICATED);
			}
			return;
		}

		TrackPointReader.init(fileTrackpoint);

		workoutProcessor.init(CyclingWorkoutReader.getUuid());
		Workout vWorkout = workoutProcessor.getWorkout();
		if (vWorkout != null) {
			equipmentInfoJson = "BES_Watch";
			vWorkout.setEquipmentInfo(equipmentInfoJson);
			vWorkout.setFitPath(fitName);
			WorkoutDatabaseHelper.save(vWorkout);
			vWorkout.setUploadStatus(Enums.UploadStatus.NotUpload);
			importWorkoutData(vWorkout);
		}
		//        createNewWorkout(vWorkout);
		onGetSportType();
		onImportPointData();
		workoutProcessor.release();

		if (syncCb != null) {
			Log.d(TAG, "onStartProcess syncCb");
			if (ifFitFileSynced(fitName)) {
				syncCb.onSyncCallback(fitName, BES_SYNC_FINISHED);
			} else {
				syncCb.onSyncCallback(fitName, BES_SYNC_STOPPED);
			}
		}
		Log.d(TAG, "onStartProcess finish-----");
	}

	//    private void createNewWorkout(Workout workout) {
	//        if (workout != null) {
	//            this.equipmentInfoJson = "BES_Watch";
	//            workout.setEquipmentInfo(this.equipmentInfoJson);
	//            WorkoutDatabaseHelper.save(workout);
	//        }
	//    }

	public void onGetSportType() {
		short vBesSportType = CyclingWorkoutReader.getSportType();
		if (vBesSportType == 5) {
			this.workoutProcessor.getWorkout().setSport(Workout.TYPE_CYCLING);
		} else if (vBesSportType == 4) {
			this.workoutProcessor.getWorkout().setSport(Workout.TYPE_INDOOR_BIKE);
		} else {
			this.workoutProcessor.getWorkout().setSport(Workout.TYPE_CYCLING);
		}
	}

	public void processPoints(TrackPointReader.CYCLING_TRACKPOINT_INFO_T besPoint) {
		SourcePoint vSource = new SourcePoint();
		vSource.setTimestamp(besPoint.time * 1000L);
		vSource.setSpeed(besPoint.speed);
		//        vSource.setAltitude(besPoint.altitude);//will be altitude fixed from on gps altitude
		vSource.setElevation((float) besPoint.elevation_gain);
		vSource.setGrade((float) besPoint.cur_slope);
		vSource.setPower((float) besPoint.power);
		vSource.setDuration(besPoint.duration);

		//        double d = Utils.DOUBLE_EPSILON;
		if (besPoint.latitude > Utils.DOUBLE_EPSILON && besPoint.longitude > Utils.DOUBLE_EPSILON) {
			GpsPoint gpsPoint = new GpsPoint();
			gpsPoint.setSpeed((float) besPoint.speed);
			gpsPoint.setLatitude(besPoint.latitude);
			gpsPoint.setLongitude(besPoint.longitude);
			gpsPoint.setAltitude(besPoint.altitude);
			gpsPoint.setSpeed((float) besPoint.speed);
			gpsPoint.setBearing((float) besPoint.bearing);
			gpsPoint.setTimestamp(besPoint.time * 1000L);
			gpsPoint.setSource(Workout.LOCATION_SOURCE_BES_WATCH);
			vSource.setGpsPoint(gpsPoint);
		}
		if (besPoint.cur_cadence > 0 || besPoint.wheelrpm > 0) {
			CadencePoint cadencePoint = new CadencePoint();
			//            this.cadencePoint = cadencePoint;
			//            cadencePoint.setSumCadence(trackpoint.getSumCadence());
			//            cadencePoint.setSumWheel(trackpoint.getSumWheel());
			//            cadencePoint.setPressure((int) trackpoint.getPressure());
			cadencePoint.setTemperature(besPoint.temperature);
			cadencePoint.setWheelRpm(besPoint.wheelrpm);
			cadencePoint.setCadence(besPoint.cur_cadence);
			cadencePoint.setSpeed(besPoint.speed);
			cadencePoint.setSource(Workout.CADENCE_SOURCE_BLE);
			vSource.setCadencePoint(cadencePoint);
		}
		if (besPoint.hr_cur > 0) {
			HeartratePoint heartratePoint = new HeartratePoint();
			heartratePoint.setHeartrate(besPoint.hr_cur);
			heartratePoint.setSource(Workout.HEARTRATE_SOURCE_BLE);
			vSource.setHeartratePoint(heartratePoint);
		}
		if (besPoint.power > 0) {
			PowerratePoint powerratePoint = new PowerratePoint();
			powerratePoint.setPowerrate((int) besPoint.power);
			powerratePoint.setSource(Workout.POWER_SOURCE_OTHER);
			vSource.setPowerratePoint(powerratePoint);
		}

		//        if (besPoint.power > 0) {
		//            IndoorbikePoint indoorbikePoint = new IndoorbikePoint();
		//            indoorbikePoint.setIndoorbikePower((int) besPoint.power);
		//            indoorbikePoint.setSource(Workout.POWER_SOURCE_OTHER);
		//            vSource.setIndoorbikePoint(indoorbikePoint);
		//        }
		//        Log.d(TAG, "processPoints: Debug version, NOT check valid source point");
		this.workoutProcessor.process(vSource);
	}

	public void onImportPointData() {
		Log.d(TAG, "onImportPointData: start ....");
		for (TrackPointReader.CYCLING_TRACKPOINT_INFO_T besPoints : TrackPointReader.mTrackPoints) {
			processPoints(besPoints);
		}
		Log.d(TAG, "onImportPointData: finish ....");
	}

	public static void importWorkoutData(Workout workout) {
		Log.d(TAG, "importWorkoutData: start ....");
		workout.setStartTime(CyclingWorkoutReader.getStartTime() * 1000L);

		workout.setDuration(CyclingWorkoutReader.getSportsDuration());//getDuration()
		workout.setPauseDuration(CyclingWorkoutReader.getPauseDuration());
		workout.setDownDuration(CyclingWorkoutReader.getDownDuration());
		workout.setUpDuration(CyclingWorkoutReader.getUpDuration());
		workout.setFlatDuration(CyclingWorkoutReader.getFlatDuration());

		workout.setDistance(CyclingWorkoutReader.getTotalDistance());
		workout.setUpDistance(CyclingWorkoutReader.getUpDistance());
		workout.setDownDistance(CyclingWorkoutReader.getDownDistance());
		workout.setFlatDistance(CyclingWorkoutReader.getFlatDistance());

		workout.setCalorie(CyclingWorkoutReader.getTotalCalorie());

		workout.setAvgSpeed(CyclingWorkoutReader.getAvgSpeed());

		workout.setMaxSpeed(CyclingWorkoutReader.getMaxSpeed());

		workout.setAvgHeartrate(CyclingWorkoutReader.getAvgHrValue());

		workout.setMaxHeartrate(CyclingWorkoutReader.getMaxHrValue());

		workout.setAvgCadence(CyclingWorkoutReader.getAvgCadenceFreq());

		workout.setMaxCadence(CyclingWorkoutReader.getMaxCadenceFreq());

		workout.setElevationGain((float) CyclingWorkoutReader.getElevationGain());

		workout.setElevationLoss((float) CyclingWorkoutReader.getElevationLoss());

		workout.setEndTime(CyclingWorkoutReader.getEndTime() * 1000L);

		if (CyclingWorkoutReader.getAvgCadenceFreq() > 0) {
			workout.setCadenceSource(Workout.CADENCE_SOURCE_OTHER);
		} else {
			workout.setCadenceSource(Workout.CADENCE_SOURCE_NONE);
		}

		if (CyclingWorkoutReader.getAvgHrValue() > 0) {
			workout.setHeartSource(Workout.HEARTRATE_SOURCE_BLE);
		} else {
			workout.setHeartSource(Workout.HEARTRATE_SOURCE_NONE);
		}

		if (CyclingWorkoutReader.getMaxPower() > 0) {
			workout.setMaxPower(CyclingWorkoutReader.getMaxPower());
			workout.setPowerSource(Workout.POWER_SOURCE_OTHER);
		} else {
			workout.setPowerSource(Workout.POWER_SOURCE_NONE);
		}
		//        if (sessionMesg.getNormalizedPower() != null) {
		//            workout.setPowerNP(sessionMesg.getNormalizedPower());
		//        }

		//        if (sessionMesg.getIntensityFactor() != null) {
		//            workout.setPowerIF(sessionMesg.getIntensityFactor());
		//        }

		//        if (sessionMesg.getTrainingStressScore() != null) {
		//            workout.setPowerTSS(sessionMesg.getTrainingStressScore());
		//        }
		//        if (sessionMesg.getAvgPower() != null) {
		//            workout.setAvgPower(sessionMesg.getAvgPower());
		//        }
		workout.setAvgPower(CyclingWorkoutReader.getAvgPower());
		//        if (sessionMesg.getNormalizedPower() != null && sessionMesg.getAvgPower() != null) {
		//            workout.setPowerVI((double) sessionMesg.getNormalizedPower() / sessionMesg.getAvgPower());
		//        }
		workout.setLocSource(Workout.LOCATION_SOURCE_BES_WATCH);
		workout.setWorkStatus(Workout.STATUS_STOPED);

		workout.setMapHidden(0);
		workout.setMapId(0);
		Log.d(TAG, "importWorkoutData: finish ....");
	}
}
